const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');
const {getSystemInfoSync} = require("../../lib/vant-weapp/dist/common/version");

//获取应用实例
const app = getApp();

Page({
    data: {
        navbarBackgroundColor: "background-color:transparent",
        newGoods: [],
        hotGoods: [],
        topics: [],
        brands: [],
        groupons: [
        ],
        floorGoods: [],
        banner: [],
        channel: [],
        coupon: [],
        goodsCount: 0,
        // 以下是分类属性
        navList: [],
        goodsList: [],
        id: 1000000,
        currentCategory: {},
        scrollLeft: 0,
        scrollTop: 0,
        scrollHeight: 0,
        page: 1,
        limit: 10,
        pages: 1, //总页数
        statusBarHeight: 0,
        height: 0,
    },

    onPageScroll: function (e) {
        // e.scrollTop 是滚动距离
        console.log('滚动距离:', e.scrollTop);
        // 你可以在这里根据滚动距离执行其他逻辑
        if (e.scrollTop > 100) {
            this.setData({
                navbarBackgroundColor: "background-color:#ffffff"
            });
        } else {
            this.setData({
                navbarBackgroundColor: "background-color:transparent"
            });
        }
    },

    onShareAppMessage: function () {
        return {
            title: '品农食尚小程序',
            desc: '',
            path: '/pages/index/index'
        }
    },

    onPullDownRefresh() {
        wx.showNavigationBarLoading() //在标题栏中显示加载
        this.getIndexData();
        this.getGoodsList();
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
    },

    getIndexData: function () {
        let that = this;
        util.request(api.IndexUrl).then(function (res) {
            if (res.errno === 0) {
                let grouponList = res.data.grouponList;
                grouponList.forEach(item => {
                    item.grouponSales = 0
                    // grouponSales 随机100-200
                    item.grouponSales = util.randomNum(100, 200)
                })
                // grouponSales
                console.log(111)
                that.setData({
                    // newGoods: res.data.newGoodsList,
                    // hotGoods: res.data.hotGoodsList,
                    // topics: res.data.topicList,
                    // brands: res.data.brandList,
                    // floorGoods: res.data.floorGoodsList,
                    banner: res.data.banner,
                    // groupons: res.data.grouponList,
                    // channel: res.data.channel,
                    // coupon: res.data.couponList
                });
            }
        });
        util.request(api.GoodsCount).then(function (res) {
            that.setData({
                goodsCount: res.data
            });
        });
    },
    onLoad: function (options) {
        var that = this;

        // 页面初始化 options为页面跳转所带来的参数
        if (options.scene) {
            //这个scene的值存在则证明首页的开启来源于朋友圈分享的图,同时可以通过获取到的goodId的值跳转导航到对应的详情页
            var scene = decodeURIComponent(options.scene);
            console.log("scene:" + scene);

            let info_arr = [];
            info_arr = scene.split(',');
            let _type = info_arr[0];
            let id = info_arr[1];

            if (_type == 'goods') {
                wx.navigateTo({
                    url: '../goods/goods?id=' + id
                });
            } else if (_type == 'groupon') {
                wx.navigateTo({
                    url: '../goods/goods?grouponId=' + id
                });
            } else {
                wx.navigateTo({
                    url: '../index/index'
                });
            }
        }

        // 页面初始化 options为页面跳转所带来的参数
        if (options.grouponId) {
            //这个pageId的值存在则证明首页的开启来源于用户点击来首页,同时可以通过获取到的pageId的值跳转导航到对应的详情页
            wx.navigateTo({
                url: '../goods/goods?grouponId=' + options.grouponId
            });
        }

        // 页面初始化 options为页面跳转所带来的参数
        if (options.goodId) {
            //这个goodId的值存在则证明首页的开启来源于分享,同时可以通过获取到的goodId的值跳转导航到对应的详情页
            wx.navigateTo({
                url: '../goods/goods?id=' + options.goodId
            });
        }

        // 页面初始化 options为页面跳转所带来的参数
        if (options.orderId) {
            //这个orderId的值存在则证明首页的开启来源于订单模版通知,同时可以通过获取到的pageId的值跳转导航到对应的详情页
            wx.navigateTo({
                url: '../ucenter/orderDetail/orderDetail?id=' + options.orderId
            });
        }

        this.getIndexData();

        if (options.id) {
            that.setData({
                id: parseInt(options.id)
            });
        }

        wx.getSystemInfo({
            success: function (res) {
                that.setData({
                    scrollHeight: res.windowHeight
                });
            }
        });


        this.getCategoryInfo();
    },
    getCategoryInfo: function () {
        let that = this;
        util.request(api.GoodsCategory, {
            id: this.data.id
        })
            .then(function (res) {

                if (res.errno == 0) {
                    that.setData({
                        navList: [...[res.data.parentCategory],...res.data.brotherCategory],
                        currentCategory: res.data.currentCategory
                    });

                    // wx.setNavigationBarTitle({
                    //     title: res.data.parentCategory.name
                    // })

                    // 当id是L1分类id时，这里需要重新设置成L1分类的一个子分类的id
                    if (res.data.parentCategory.id == that.data.id) {
                        that.setData({
                            id: res.data.parentCategory.id
                        });
                    }

                    //nav位置
                    let currentIndex = 0;
                    let navListCount = that.data.navList.length;
                    for (let i = 0; i < navListCount; i++) {
                        currentIndex += 1;
                        if (that.data.navList[i].id == that.data.id) {
                            break;
                        }
                    }
                    if (currentIndex > navListCount / 2 && navListCount > 5) {
                        that.setData({
                            scrollLeft: currentIndex * 60
                        });
                    }
                    that.getGoodsList();

                } else {
                    //显示错误信息
                }

            });
    },
    getGoodsList: function () {
        var that = this;

        util.request(api.GrouponUrl, {
            categoryId: that.data.id,
            page: that.data.page,
            limit: that.data.limit
        })
            .then(function (res) {
                var arr1 = that.data.goodsList; //从data获取当前datalist数组
                var arr2 = res.data.list; //从此次请求返回的数据中获取新数组
                console.log(arr2,"arr2")
                arr2.forEach(item=>{
                    item.expireTime = item.expireTime.substring(0, 16);
                    item.pickUpTime = item.pickUpTime.substring(0, 16);
                })
                arr1 = arr1.concat(arr2); //合并数组
                that.setData({
                    goodsList: arr1,
                    pages: res.data.pages //得到总页数
                });
            });
    },
    switchCate: function(event) {
        if (this.data.id == event.currentTarget.dataset.id) {
            return false;
        }
        var that = this;
        var clientX = event.detail.x;
        var currentTarget = event.currentTarget;
        if (clientX < 60) {
            that.setData({
                scrollLeft: currentTarget.offsetLeft - 60
            });
        } else if (clientX > 330) {
            that.setData({
                scrollLeft: currentTarget.offsetLeft
            });
        }
        this.setData({
            id: event.currentTarget.dataset.id,
            page:1, //从第一页开始查
            goodsList:[]
        });

        this.getCategoryInfo();
    },
    //触底开始下一页
    onReachBottom: function () {
        var that = this;

        var pagenum = that.data.page + 1; //获取当前页数并+1
        if (pagenum <= that.data.pages) {
            that.setData({
                page: pagenum, //更新当前页数
            })
            that.getGoodsList();//重新调用请求获取下一页数据
        } else {
            util.showErrorToast("已经是最后一页了");
        }
    },
    onReady: function () {
        // 页面渲染完成
        const {statusBarHeight} = getSystemInfoSync();
        this.setData({
            statusBarHeight,
            height: 46 + statusBarHeight,
        });
    },
    onShow: function () {
        // 页面显示
    },
    onHide: function () {
        // 页面隐藏
    },
    onUnload: function () {
        // 页面关闭
    },
    getCoupon(e) {
        let couponId = e.currentTarget.dataset.index
        util.request(api.CouponReceive, {
            couponId: couponId
        }, 'POST').then(res => {
            if (res.errno === 0) {
                wx.showToast({
                    title: "领取成功"
                })
            } else {
                util.showErrorToast(res.errmsg);
            }
        })
    },
})